<?php

class DynamicFormModel extends CFormModel {
        
    private $_dynamicData = array();
    private $_dynamicFields = array();
    private $_dynamicLabels = array();
    private $_dynamicRules = array();
    
    public function __construct($model, $scenario='')
	{
        parent::__construct($scenario);
        
        foreach ($model->sections as $section) {
            foreach ($section->fields as $field) {
                $this->_dynamicFields[$field->id] = 1;
                // Get field names
                $this->_dynamicLabels[$field->id] = $field->label;
                // Get field validations
                $validations = json_decode($field->validations);
                foreach ($validations as $validation) {
                    if($validation == Field::VALIDATION_TYPE_DIGITS) {
                        $this->_dynamicRules[] = array($field->id,'numerical','integerOnly'=>true);
                    } else {
                        $this->_dynamicRules[] = array($field->id,$validation);
                    }
                }
            }
        }
    }
    
    public function rules() {
        return $this->_dynamicRules;
    }

    public function attributeNames() {
        return array_merge(
            parent::attributeNames(),
            array_keys($this->_dynamicFields)
        );
    }
    
    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return $this->_dynamicLabels;
    }

    /**
     * Returns the value for a dynamic attribute, if not, falls back to parent
     * method
     * 
     * @param type $name
     * @return type 
     */
    public function __get($name) {
        if (!empty($this->_dynamicFields[$name])) {
            if (!empty($this->_dynamicData[$name])) {
                return $this->_dynamicData[$name];
            } else {
                return null;
            }
        } else {
            return parent::__get($name);
        }
    }

    /**
     * Overrides the setter to store dynamic data.
     * 
     * @param type $name
     * @param type $val 
     */
    public function __set($name, $val) {
        if (!empty($this->_dynamicFields[$name])) {
            $this->_dynamicData[$name] = $val;
        } else {
            parent::__set($name, $val);
        }
    }
        
}